import cv2
import numpy as np
from utils import LinearTran, ColorsSave, ExpTran, enrenge, duibi, quchubei, addpic, turncolorBG



_DILATE_KERNEL = np.array([[0, 0, 1, 0, 0],
                           [0, 0, 1, 0, 0],
                           [1, 1, 1, 1, 1],
                           [0, 0, 1, 0, 0],
                           [0, 0, 1, 0, 0]], dtype=np.uint8)

# 对图片进行膨胀计算，使得掩码膨胀一圈，以免留下边缘没有被修复
def dilate(img):
    """
    对图片进行膨胀计算
    :param img:
    :return:
    """
    dilated = cv2.dilate(img, _DILATE_KERNEL)
    return dilated


def blend_two_images(path):
    img = cv2.imread(path,cv2.IMREAD_UNCHANGED)

    timg = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    _, timg = cv2.threshold(timg, timg.mean(), 255, cv2.THRESH_BINARY)  # 做MASK与原图操作，背景变白，字体公章不变

    cv2.imshow('origial', img)
    print(img.shape)
    b = np.zeros((img.shape[0], img.shape[1]), dtype=img.dtype)
    g = np.zeros((img.shape[0], img.shape[1]), dtype=img.dtype)
    r = np.zeros((img.shape[0], img.shape[1]), dtype=img.dtype)

    # 复制图像通道里的数据
    b[:, :] = img[:, :, 0]  # 复制 b 通道的数据
    g[:, :] = img[:, :, 1]  # 复制 g 通道的数据
    r[:, :] = img[:, :, 2]  # 复制 r 通道的数据


    # 灰色背景变白
    # tr = 255 - r * (255 - timg)
    # tb = 255 - b * (255 - timg)
    # tg = 255 - g * (255 - timg)
    # cv2.imshow('tr', tr)
    # pimg = np.dstack((tb,tg,tr))
    # cv2.imshow('ping',pimg)

    tr = turncolorBG(r, timg)
    tb = turncolorBG(b, timg)
    tg = turncolorBG(g, timg)
    pimg = np.dstack((tb, tg, tr))
    cv2.imshow('pimg', pimg)

    # mask
    # ir = LinearTran(r,a=1,b=50)
    im = LinearTran(tr, a=2, b=-30)
    ib = ExpTran(tr, 0.2, gama=0.5)
    itc = addpic(im, ib)
    # cv2.imshow('1',im)
    # cv2.imshow('2', ib)
    # cv2.imshow('3', itc)
    itc = LinearTran(itc,1,-50)
    #cv2.imshow('4', itc)

    kernel = np.ones((3,3), np.uint8)*255
    itc = cv2.erode(itc, kernel)

    ic = 255 - itc
    _, ic = cv2.threshold(ic,100,255,cv2.THRESH_BINARY)
    cv2.imshow('mask', ic)
    cv2.imwrite('mask.jpg',ic)

    # dr = tr + ic
    # db = tb + ic
    # dg = tg + ic
    #
    # par = [1,50]
    # db = LinearTran(db, a=par[0], b=par[1])
    # dg = LinearTran(dg, a=par[0], b=par[1])
    # dr = LinearTran(dr, a=par[0], b=par[1])
    #
    # dst = np.dstack((db,dg,dr))

    dst = cv2.inpaint(pimg, ic, 3, cv2.INPAINT_TELEA)

    cv2.imshow('1_result1.jpg', dst)
    cv2.imwrite('1_result1.jpg', dst)

    cv2.waitKey()
    cv2.destroyAllWindows()
    return


blend_two_images('12.jpg')
